package com.shqcjd.preinstallglass.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.open.androidtvwidget.bridge.EffectNoDrawBridge;
import com.open.androidtvwidget.bridge.OpenEffectBridge;
import com.open.androidtvwidget.view.FrameMainLayout;
import com.open.androidtvwidget.view.MainUpView;
import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.api.ApiService;
import com.shqcjd.preinstallglass.app.MyApp;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallglass.model.ResponseData;
import com.shqcjd.preinstallglass.model.eventbus.CreateVideotape;
import com.shqcjd.preinstallglass.model.pojo.EquipmentInspectionBean;
import com.shqcjd.preinstallglass.model.pojo.IntentEquipmentBean;
import com.shqcjd.preinstallglass.ui.activity.input.NumberInputActivity;
import com.shqcjd.preinstallglass.ui.activity.remote.ExpertTypeActivity;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;
import com.shqcjd.preinstallglass.util.Config;
import com.shqcjd.preinstallglass.util.NumberValidationUtils;
import com.shqcjd.preinstallglass.util.ToastUtils;
import com.shqcjd.preinstallglass.util.UIUtils;
import com.shqcjd.preinstallglass.util.VideotapeUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class NewEquipmentInspectionActivity extends BaseActivity {

    @BindView(R.id.tv_equment_inspection_title)
    TextView tvEqumentInspectionTitle;
    @BindView(R.id.ll_equipment_inspection)
    LinearLayout llEquipmentInspection;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_last)
    TextView tvLast;
    @BindView(R.id.tv_process)
    TextView tvProcess;
    @BindView(R.id.cb_equment_inspection_switch)
    CheckBox cbEqumentInspectionSwitch;

    @BindView(R.id.btn_finish)
    public Button btnFinish;
    @BindView(R.id.btn_guide)
    Button btnGuide;

    @BindView(R.id.mainUpView1)
    MainUpView mMainUpView;
    @BindView(R.id.main_lay)
    FrameMainLayout main_lay11;
    OpenEffectBridge mOpenEffectBridge;
    View mOldFocus;


    private int tId;
    private String kks, nextKks;
    List<EquipmentInspectionBean.PartsBean> mList = new ArrayList<>();
    private Context context;
    private final int INPUT_FINISH = 15156;
    private final int END_CODE = 12312;
    private static final int REQUEST_COLOR_CODE = 111;
    private static final int REQUEST_QCODE_CODE = 110;

    private EquipmentInspectionBean.PartsBean.ItemsBean.MyBean itemBean;
    private EquipmentInspectionBean.PartsBean.ItemsBean iBean;

    private int epId;
    private int prid;

    private int parentPosition = 0;
    private int childPosition = 0;

    private boolean isInput; //判断是否是输入页面，如何是输入页面则不需要重新开录像

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_new_equipment_inspection;
    }

    @Override
    public void init() {
        super.init();
        context = this;
        tId = getIntent().getIntExtra("tId", -1);
        kks = getIntent().getStringExtra("kks");
    }

    @Override
    protected String getVoiceContent() {
        return "|返回|上一项|下一项|正常|异常|远程指导|输入|颜色识别|扫描;";
    }

    @Override
    protected void onVoiceResult(String result) {
        Log.e("tou", result+"-----");
        Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
        switch (result) {
            case "返回":
                finish();
                break;
            case "上一项":
                lastView();
                break;
            case "下一项":
                nextView();
                break;
            case "正常":
                putCheckResultHttp(edChildValue == null ? "" :edChildValue.getText().toString(), 1, cId, childTrue);
                break;
            case "异常":
                putCheckResultHttp(edChildValue == null ? "" :edChildValue.getText().toString(), -1, cId, childFalse);
                break;
            case "远程指导":
                isInput = false;
                VideotapeUtil.getInstance().finishVideotape(new VideotapeUtil.OnFinishVideotapeListener() {
                    @Override
                    public void onInitFinish() {
                        showWaitingDialog("处理中...");
                    }

                    @Override
                    public void onFinishVideotape() {
                        hideWaitingDialog();
                        startActivity(new Intent(context, ExpertTypeActivity.class));
                    }
                });
                break;
            case "输入":
                if(edChildValue!=null){
                    Intent it = new Intent(context, NumberInputActivity.class);
                    it.putExtra("str", edChildValue.getText().toString().trim());
                    startActivityForResult(it, INPUT_FINISH);
                }
                break;
            case "颜色识别":
                if(btn_chile_color.getVisibility() == View.VISIBLE){
                    RxPermissions permissions = new RxPermissions(NewEquipmentInspectionActivity.this);
                    permissions.setLogging(true);
                    permissions.request(
                            Manifest.permission.CAMERA)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean) {
                                        //发送eventbus 关闭全程录像camera资源后打开扫描颜色识别
                                        isInput = false;
//                                        EventBus.getDefault().post(new FinishVideotape(AppConstant.COLOUR_DATA_CODE));
                                        VideotapeUtil.getInstance().finishVideotape(new VideotapeUtil.OnFinishVideotapeListener() {
                                            @Override
                                            public void onInitFinish() {
                                                showWaitingDialog("处理中...");
                                            }

                                            @Override
                                            public void onFinishVideotape() {
                                                hideWaitingDialog();
                                                startActivityForResult(new Intent(context, ColorActivity.class), REQUEST_COLOR_CODE);
                                            }
                                        });

                                    } else {

                                    }
                                }
                            });
                }
                break;
            case "扫描":
                if(btn_chile_qcode.getVisibility() == View.VISIBLE){

                }
                break;
        }
    }


    @Override
    public void initView() {
        super.initView();
        tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextView();
            }
        });

        tvLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lastView();
            }
        });

        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnGuide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isInput = false;
                VideotapeUtil.getInstance().finishVideotape(new VideotapeUtil.OnFinishVideotapeListener() {
                    @Override
                    public void onInitFinish() {
                        showWaitingDialog("处理中...");
                    }

                    @Override
                    public void onFinishVideotape() {
                        hideWaitingDialog();
                        startActivity(new Intent(context, ExpertTypeActivity.class));
                    }
                });
            }
        });
        cbEqumentInspectionSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                openOrCloseSwitchHttp();
            }
        });

        mMainUpView.setEffectBridge(new EffectNoDrawBridge());
        mOpenEffectBridge = (OpenEffectBridge) mMainUpView.getEffectBridge();
        Drawable testDrawable = null;
        mMainUpView.setUpRectDrawable(testDrawable); // 设置边框图片
        mMainUpView.setUpRectResource(R.drawable.test_rectangle); // 设置边框图片.


        main_lay11.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(final View oldFocus, final View newFocus) {

                if (newFocus != null)
//                    newFocus.bringToFront(); // 防止放大的view被压在下面. (建议使用MainLayout)
                    mMainUpView.setFocusView(newFocus, mOldFocus, 1.0f);
                mOldFocus = newFocus; // 4.3以下需要自己保存.
                // 测试是否让边框绘制在下面，还是上面. (建议不要使用此函数)
//                if (newFocus != null) {
//                    testTopDemo(newFocus, scale);
//                }
            }
        });

        getData();
    }

    private void getData() {
        ApiService.equipmentInspectionHttp(tId, kks.replace("#", "%23"))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<EquipmentInspectionBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<EquipmentInspectionBean> responseData) {
                        if (responseData.retCode != 10000) {
                            return;
                        }
                        if(responseData.data.parts.size()==0){
                            return;
                        }
                        epId = responseData.data.id;
                        nextKks = responseData.data.next.kks;
                        tvEqumentInspectionTitle.setText("当前设备" + responseData.data.name);
                        cbEqumentInspectionSwitch.setChecked(responseData.data.running);
                        mList.addAll(responseData.data.parts);
                        initPosition();
                        initListView();

                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void openOrCloseSwitchHttp() {
        ApiService.openOrCloseSwitchHttp(kks.replace("#", "%23"))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode != 10000) {
                            hideWaitingDialog();
                            return;
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    TextView edChildValue = null;
    RadioButton childTrue, childFalse;
    int cId = 0;
    Button btn_chile_color;
    Button btn_chile_number;
    Button btn_chile_qcode;

    private void initListView(){
        llEquipmentInspection.removeAllViews();
        View v = LayoutInflater.from(context).inflate(R.layout.item_equipment_inspect_title, null);
        TextView title = v.findViewById(R.id.tv_title);
        title.setText(mList.get(parentPosition).part_name);
        llEquipmentInspection.addView(v);
        EquipmentInspectionBean.PartsBean.ItemsBean c = mList.get(parentPosition).items.get(childPosition);
        View vChild;
        TextView childTitle;
        TextView chileStandard;
        TextView childState;
        TextView childCode;

        if (c.check_method.size() == 0) {
            vChild = LayoutInflater.from(context).inflate(R.layout.item_equipment_inspect_common, null);
        } else {
            if (c.check_type == 1) {
                vChild = LayoutInflater.from(context).inflate(R.layout.item_equipment_inspect_color, null);
            } else {
                vChild = LayoutInflater.from(context).inflate(R.layout.item_equipment_inspect_number, null);
                edChildValue = vChild.findViewById(R.id.ed_child_value);
                if (!c.value.equals("-1")) {
                    edChildValue.setText(c.value + "");
                }
                edChildValue.setTag(c.id);
                edChildValue.setInputType(InputType.TYPE_NULL);
                edChildValue.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        iBean = c;
                        isInput = true;
                        Intent it = new Intent(context, NumberInputActivity.class);
                        startActivityForResult(it, INPUT_FINISH);
                    }
                });

            }


             btn_chile_color = vChild.findViewById(R.id.btn_chile_color);
             btn_chile_number = vChild.findViewById(R.id.btn_chile_number);
             btn_chile_qcode = vChild.findViewById(R.id.btn_chile_qcode);
            TextView tv_child_see = vChild.findViewById(R.id.tv_child_see);
            TextView tv_child_hear = vChild.findViewById(R.id.tv_child_hear);

            for (int k = 0; k < c.check_method.size(); k++) {
                if (c.check_method.get(k).type == 5) {
                    btn_chile_color.setVisibility(View.VISIBLE);
                }
                if (c.check_method.get(k).type == 3) {
                    btn_chile_number.setVisibility(View.VISIBLE);
                }
                if (c.check_method.get(k).type == 4) {
                    btn_chile_qcode.setVisibility(View.VISIBLE);
                    btn_chile_qcode.setTag(c.check_method.get(k));
                }
                if (c.check_method.get(k).type == 1) {
                    tv_child_see.setVisibility(View.VISIBLE);
                    tv_child_see.setTag(c.check_method.get(k));
                }
                if (c.check_method.get(k).type == 2) {
                    tv_child_hear.setVisibility(View.VISIBLE);
                    tv_child_hear.setTag(c.check_method.get(k));
                }
            }
            btn_chile_number.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
            btn_chile_color.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RxPermissions permissions = new RxPermissions(NewEquipmentInspectionActivity.this);
                    permissions.setLogging(true);
                    permissions.request(
                            Manifest.permission.CAMERA)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean) {
                                        //发送eventbus 关闭全程录像camera资源后打开扫描颜色识别
                                        isInput = false;
//                                        EventBus.getDefault().post(new FinishVideotape(AppConstant.COLOUR_DATA_CODE));
                                        VideotapeUtil.getInstance().finishVideotape(new VideotapeUtil.OnFinishVideotapeListener() {
                                            @Override
                                            public void onInitFinish() {
                                                showWaitingDialog("处理中...");
                                            }

                                            @Override
                                            public void onFinishVideotape() {
                                                hideWaitingDialog();
                                                startActivityForResult(new Intent(context, ColorActivity.class), REQUEST_COLOR_CODE);
                                            }
                                        });
                                    } else {

                                    }
                                }
                            });
                }
            });

            //扫描按钮
            btn_chile_qcode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemBean = (EquipmentInspectionBean.PartsBean.ItemsBean.MyBean) v.getTag();
                    if (itemBean.data.equals("")) {
                        Toast.makeText(context, "后台数据异常", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    RxPermissions permissions = new RxPermissions(NewEquipmentInspectionActivity.this);
                    permissions.setLogging(true);
                    permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean) {
                                        //发送eventbus 关闭全程录像camera资源后 打开扫描二维码页面
                                        isInput = false;
//                                        EventBus.getDefault().post(new FinishVideotape(AppConstant.GET_SENSOR_DATA_CODE));
                                        VideotapeUtil.getInstance().finishVideotape(new VideotapeUtil.OnFinishVideotapeListener() {
                                            @Override
                                            public void onInitFinish() {
                                                showWaitingDialog("处理中...");
                                            }

                                            @Override
                                            public void onFinishVideotape() {
                                                hideWaitingDialog();
                                                startActivityForResult(new Intent(NewEquipmentInspectionActivity.this, QRcodeActivity.class), REQUEST_QCODE_CODE);

                                            }
                                        });
                                    } else {
                                        ToastUtils.show(NewEquipmentInspectionActivity.this, "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                    }
                                }
                            });
                }
            });
        }
        childTitle = vChild.findViewById(R.id.tv_child_title);
        chileStandard = vChild.findViewById(R.id.tv_child_standard);
        childState = vChild.findViewById(R.id.tv_child_state);
        childTrue = vChild.findViewById(R.id.rb_child_state_true);
        childFalse = vChild.findViewById(R.id.rb_child_state_false);
        childCode = vChild.findViewById(R.id.tv_child_code);

        childTitle.setText(c.name);
        childState.setText(c.last_result == 1 ? "正常" : "异常");
        childCode.setText((childPosition+1)+"");
        if (c.last_result == 1) {
            childState.setText("正常");
        } else if (c.last_result == 2) {
            childState.setText("异常");
        }
        chileStandard.setText(c.stand);
        if (c.result == 1) {
            childTrue.setChecked(true);
        } else if (c.result == 2) {
            childFalse.setChecked(true);
        }

        llEquipmentInspection.addView(vChild);

        childTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                putCheckResultHttp(edChildValue == null ? "" :edChildValue.getText().toString(), 1, c.id, v);
            }
        });

        childFalse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                putCheckResultHttp(edChildValue == null ? "" : edChildValue.getText().toString(), -1, c.id, v);
            }
        });
        cId = c.id;
        getProcess();

        tvNext.setNextFocusRightId(R.id.cb_equment_inspection_switch);
        cbEqumentInspectionSwitch.setNextFocusLeftId(R.id.tv_next);
        tvLast.setNextFocusLeftId(R.id.btn_finish);
        cbEqumentInspectionSwitch.setNextFocusRightId(R.id.rb_child_state_true);
        btnFinish.setNextFocusLeftId(R.id.tv_last);
        if(edChildValue!=null){
            btnFinish.setNextFocusRightId(R.id.ed_child_value);
            edChildValue.setNextFocusLeftId(R.id.btn_finish);
            edChildValue.setNextFocusRightId(R.id.rb_child_state_true);
        }else{
            btnFinish.setNextFocusRightId(R.id.rb_child_state_true);
        }

    }

    private void nextView(){
        if(mList.get(parentPosition).items.size()<=childPosition+1){
            if(mList.size()<=parentPosition+1){
                if(isEnd()){
                    if (!nextKks.equals("")) {
                        isInspectionData(nextKks);
                    } else {
                        Toast.makeText(context, "所有设备巡检完毕", Toast.LENGTH_SHORT).show();
                        isInput = false;
//                        EventBus.getDefault().post(new FinishVideotape(0));
                        VideotapeUtil.getInstance().finishVideotape(new VideotapeUtil.OnFinishVideotapeListener() {
                            @Override
                            public void onInitFinish() {
                                showWaitingDialog("处理中...");
                            }

                            @Override
                            public void onFinishVideotape() {
                                hideWaitingDialog();
                                finish();
                            }
                        });
                    }
                }else{
                    resetSearchPosition();
                }
            }else{
                parentPosition++;
                childPosition = 0;
                initPosition();
            }
        }else{
            childPosition++;
            initPosition();
        }
        initListView();
    }

    private void lastView(){
        if(childPosition==0){
            if(parentPosition==0){
                ToastUtils.showShort(context, "当前已经是第一条了");
                return;
            }else{
                parentPosition--;
                childPosition = mList.get(parentPosition).items.size()-1;
            }
        }else{
            childPosition--;
        }
        initListView();
    }


    /**
     * 寻找未巡检的子项位置
     */
    private void initPosition(){
        int a = childPosition;
        for(int i=parentPosition; i<mList.size(); i++){
            for(int j=a; j<mList.get(i).items.size(); j++){
                if(mList.get(i).items.get(j).result == 0){
                    parentPosition = i;
                    childPosition = j;
                    return;
                }
                a = 0;
            }
        }
    }

    /**
     * 获取当前巡检的进度
     */
    private void getProcess(){
        int a = 0;
        int b = 0;
        for(int i=0; i<mList.size(); i++){
            for(int j=0; j<mList.get(i).items.size(); j++){
                if(mList.get(i).items.get(j).result != 0){
                    b++;
                }
                a++;
            }
        }
        tvProcess.setText("巡检进度"+b+"/"+a);
    }

    /**
     * 从第一个开始寻找未巡检过的
     */
    private void resetSearchPosition(){
        parentPosition = 0;
        childPosition = 0;
        initPosition();
    }

    /**
     * 判断所有的是否都巡检了
     */
    private boolean isEnd(){
        for(int i=0; i<mList.size(); i++){
            for(int j=0; j<mList.get(i).items.size(); j++){
                if(mList.get(i).items.get(j).result == 0){
                    return false;
                }
            }
        }
        return true;
    }


    private String value;
    private int eId;
    private void putCheckResultHttp(String v, int status, int e, View view) {
        eId = e;
        value = v;
        Map<String, String> map = new HashMap<>();
        map.put("task_id", tId + "");
        map.put("equipment_part_item_id", eId + "");
        map.put("value", value);
        map.put("status", status + "");
        map.put("equipment_id", epId + "");

        ApiService.putCheckResultHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> responseData) {
                        hideWaitingDialog();
                        if (responseData.retCode == 10000) {
                            mList.get(parentPosition).items.get(childPosition).result = status==-1?2:1;
                            if (status == -1) {
                                //进入异常页面
                                prid =  responseData.data;
                                //发送eventbus 关闭全程录像camera资源后 打开异常页面
                                Logger.i("释放:---------putCheckResultHttp");
                                isInput = false;
//                                EventBus.getDefault().post(new FinishVideotape(AppConstant.ABNORMAL_CODE));
                                VideotapeUtil.getInstance().finishVideotape(new VideotapeUtil.OnFinishVideotapeListener() {
                                    @Override
                                    public void onInitFinish() {
                                        showWaitingDialog("处理中...");
                                    }

                                    @Override
                                    public void onFinishVideotape() {
                                        hideWaitingDialog();
                                        Intent it = new Intent(context, AbnormalActivity.class);
                                        it.putExtra("prid", prid);
                                        it.putExtra("tId",tId);
                                        it.putExtra("epId",epId);
                                        it.putExtra("eId",eId);
                                        it.putExtra("value",value);
                                        startActivityForResult(it, END_CODE);

                                    }
                                });
                            } else {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        nextView();
                                    }
                                }, 1500);
                            }
                        } else {
                            RadioButton radioButton = (RadioButton) view;
                            radioButton.setChecked(false);
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        Toast.makeText(context, "网络连接异常", Toast.LENGTH_SHORT).show();
                        RadioButton radioButton = (RadioButton) view;
                        radioButton.setChecked(false);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_QCODE_CODE == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            if (value.equals(kks)) {
                getButtonData(itemBean.data, iBean.data_type, itemBean.equipment_part_item_id, iBean);
            } else {
                Toast.makeText(context, "设备二维码有误，请确认后重新扫描", Toast.LENGTH_SHORT).show();
            }

        }
        if (requestCode == END_CODE) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    nextView();
                }
            }, 1500);
        }

        if (resultCode == REQUEST_COLOR_CODE) {
            String result = data.getStringExtra("result");
            if(result==null){
                return;
            }
            if (result.equals("异常")) {
                RadioButton r = childFalse;
                r.performClick();
            } else {
                RadioButton r = childTrue;
                r.performClick();
            }
        }

        if(requestCode == INPUT_FINISH && RESULT_OK == resultCode){
            String s = data.getStringExtra("input_key");
            if (s.equals("")) {
                return ;
            }
            if (!NumberValidationUtils.isRealNumber(s)) {
                edChildValue.setText("");
                Toast.makeText(context, "请确认当前输入的是数字", Toast.LENGTH_SHORT).show();
                return ;
            }
            mList.get(parentPosition).items.get(childPosition).value = s;
            edChildValue.setText(s);
            if(iBean==null||iBean.min==null||iBean.max==null||!NumberValidationUtils.isRealNumber(iBean.min)||!NumberValidationUtils.isRealNumber(iBean.max)){
                Toast.makeText(context, "后台返回数据异常", Toast.LENGTH_SHORT).show();
                return;
            }
            if (Double.parseDouble(iBean.min) < Double.parseDouble(s) && Double.parseDouble(s) < Double.parseDouble(iBean.max)) {
                RadioButton rb = childTrue;
                rb.performClick();
            } else {
                RadioButton rb = childFalse;
                rb.performClick();
            }
        }

    }

    private void getButtonData(String url, String type, int equipment_part_item_id, EquipmentInspectionBean.PartsBean.ItemsBean mBean) {
        ApiService.equipmentInspectionButtonHttp(url, epId, type, equipment_part_item_id)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<String> responseData) {
                        if (responseData.retCode != 10000) {
                            hideWaitingDialog();
                            return;
                        }
                        if (responseData.data.equals("")) {
                            Toast.makeText(context, "未读取到数据", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        TextView editText = edChildValue;
                        editText.setText(responseData.data);
                        Double max = Double.parseDouble(mBean.max);
                        Double min = Double.parseDouble(mBean.min);
                        Double num = Double.parseDouble(responseData.data);
                        if (min < num && num < max) {
                            RadioButton rb = childTrue;
                            rb.setChecked(true);
                        } else {
                            RadioButton rb = childFalse;
                            rb.setChecked(true);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //结束全程录像
        VideotapeUtil.getInstance().finishVideotape(new VideotapeUtil.OnFinishVideotapeListener() {
            @Override
            public void onInitFinish() {

            }

            @Override
            public void onFinishVideotape() {

            }
        });
    }

    private void isInspectionData(String kksStr) {
        ApiService.intentEquipmentHttp(kksStr, tId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<IntentEquipmentBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<IntentEquipmentBean> responseData) {
                        if (responseData.retCode == 10000) {
                            if (responseData.data.check_gps) {
                                RxPermissions permissions = new RxPermissions(NewEquipmentInspectionActivity.this);
                                permissions.setLogging(true);
                                permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                                        .subscribe(new Consumer<Boolean>() {
                                            @Override
                                            public void accept(Boolean aBoolean) throws Exception {
                                                if (aBoolean) {
                                                    MyApp.startLocation();
                                                    MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
                                                        @Override
                                                        public void onLocationInterface(AMapLocation aMapLocation) {
                                                            LatLng desLatLng = UIUtils.getGpsChangeLocation(responseData.data.latitude, responseData.data.longitude, context);
                                                            //当前坐标
                                                            double cLongitude = aMapLocation.getLongitude();
                                                            double cLatitude = aMapLocation.getLatitude();
                                                            float distance = AMapUtils.calculateLineDistance(desLatLng, new LatLng(cLatitude, cLongitude));
                                                            if (distance < Config.INSPECTION_DISTANCE) {
                                                                if (responseData.data.isgroup) {
                                                                    Intent it = new Intent(context, InspectionStandardActivity.class);
                                                                    it.putExtra("kks", kksStr);
                                                                    it.putExtra("tId", tId);
                                                                    startActivity(it);
                                                                } else {
                                                                    Intent it = new Intent(context, NewEquipmentInspectionActivity.class);
                                                                    it.putExtra("tId", tId);
                                                                    it.putExtra("kks", kksStr);
                                                                    startActivity(it);
                                                                }
                                                                finish();
                                                            } else {
                                                                Toast.makeText(context, "当前位置距离巡检点超过了"+Config.INSPECTION_DISTANCE+"米", Toast.LENGTH_SHORT).show();
                                                            }
                                                        }
                                                    });
                                                } else {
                                                    ToastUtils.show(NewEquipmentInspectionActivity.this, "巡检需要获取定位的权限", Toast.LENGTH_SHORT);
                                                }
                                            }
                                        });
                            } else {
                                if (responseData.data.isgroup) {
                                    Intent it = new Intent(context, InspectionStandardActivity.class);
                                    it.putExtra("kks", kksStr);
                                    it.putExtra("tId", tId);
                                    startActivity(it);
                                } else {
                                    Intent it = new Intent(context, NewEquipmentInspectionActivity.class);
                                    it.putExtra("tId", tId);
                                    it.putExtra("kks", kksStr);
                                    startActivity(it);
                                }
                                finish();
                            }
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                        Toast.makeText(context, "任务不存在", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }


    /**
     * 后台创建远程指导接口
     */
    private void createGuideHandle(String roomId,String userId) {
        if (kks == null || tId == -1) {
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("user_id", userId);
        map.put("room_id", roomId);
        map.put("kks", kks);
        map.put("flights_task_id", tId+"");

        ApiService.createGuide(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);

                    }

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData != null && retData.retCode == 10000) {
                            guideHandle("0",roomId);
                        }


                    }

                    @Override
                    public void _onError(String errorMessage) {
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void guideHandle(String handle,String roomId) {
        Map<String, String> map = new HashMap<>();
        map.put("roomId", roomId);
        map.put("operation", handle);//	0:开始录制、1:结束录制
        map.put("guideStatus", "1");//0:专家指导,1:全程录像，operation为(0:开始录制)该参数有效
        ApiService.handleGuide(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                    }

                    @Override
                    public void _onError(String errorMessage) {
                    }
                });

    }



    @Override
    protected void onResume() {
        super.onResume();
        if (kks != null) {
            //开启全程录像
//            EventBus.getDefault().post(new CreateVideotape(NewEquipmentInspectionActivity.this, kks,tId + ""));
            //开启全程录像
            if (!isInput) {//数字输入页面返回后不需要重新开启录像
                Logger.i("数字输入:onResume 录像");
//                EventBus.getDefault().post(new CreateVideotape(NewEquipmentInspectionActivity.this, kks,null,null, null,tId + ""));
                CreateVideotape createVideotape = new CreateVideotape(this, kks,tId + "");
                VideotapeUtil.getInstance().createVideotape(this,true, createVideotape, new VideotapeUtil.OnVideotapeListener() {
                    @Override
                    public void onVideotape(String channel, int uid, int elapsed) {
                        createGuideHandle(channel,uid+"");
                    }
                });

                isInput = false;
            }
        }
    }
}
